package cn.edu.nju.setting;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.edu.nju.R;
import cn.edu.nju.storage.StoreDataProvider;

import android.app.Activity;

public class SettingProvider {
	private static SettingProvider provider;
	private List<FilterRule> rules;
	private boolean hasRuleDeleted = false;
	private boolean hasRuleAdded = false;
	private String serverUrl;
	private Activity activity;

	public static SettingProvider getInstance(Activity activity) {
		if (provider == null) {
			provider = new SettingProvider(activity);
		}
		return provider;
	}

	private SettingProvider(Activity activity) {
		this.activity = activity;
		serverUrl = activity.getString(R.string.server_url) + "tag.php";
	}

	public List<FilterRule> getFilterRules() {
		rules = new ArrayList<FilterRule>();

		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(
					serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			entity.addPart("id", new StringBody("" + StoreDataProvider.getInstance(activity).getUserId()));
			entity.addPart("option", new StringBody("getRules"));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			JSONArray array = new JSONArray(context);

			for (int i = 0; i < array.length(); i++) {
				JSONObject rule = array.getJSONObject(i);
				JSONArray array_tags = rule.getJSONArray("tags");
				List<String> tags = new ArrayList<String>();

				for (int j = 0; j < array_tags.length(); j++) {
					tags.add(array_tags.getJSONObject(j).getString("tag"));
				}
				
				rules.add(new FilterRule(rule.getString("name"), (rule
						.getInt("isUsed") == 1), tags, rule.getLong("id"),activity));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return rules;

	}

	public FilterRule getFilterRule(int position) {
		return rules.get(position);
	}

	public void removeRule(int position) {
		try {
			String serverUrl = activity.getString(R.string.server_url) + "rules.php";
			FilterRule rule = rules.get(position);
			
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(
					serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			entity.addPart("option", new StringBody("remove"));
			entity.addPart("id", new StringBody("" + rule.getId()));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();
			
			if(context.equals(new String("OK"))){
				rules.remove(position);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void addRule(FilterRule rule) {
		
		try {
			String serverUrl = activity.getString(R.string.server_url) + "rules.php";
			
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(
					serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			
			

			entity.addPart("option", new StringBody("add"));
			entity.addPart("id", new StringBody("" + StoreDataProvider.getInstance(activity).getUserId()));
			entity.addPart("name",new StringBody(rule.getRuleName(),Charset.forName("utf-8")));
			List<String> tags = rule.getTags();
			
			entity.addPart("num", new StringBody("" + tags.size()));
			
			for (int i = 0; i < tags.size(); i++) {
				entity.addPart("tag" + i, new StringBody(tags.get(i), Charset.forName("utf-8")));
			}

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();
			
			rule.setId(Long.parseLong(context));
			rules.add(rule);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean getHasRuleDeleted() {
		return hasRuleDeleted;
	}

	public void setHasRuleDeleted(boolean hasDeleted) {
		this.hasRuleDeleted = hasDeleted;
	}

	public boolean getHasRuleAdded() {
		return hasRuleAdded;
	}

	public void setHasRuleAdded(boolean hasAdded) {
		this.hasRuleAdded = hasAdded;
	}
}
